const { ipcRenderer } = window.require('electron');
const { dialog } = window.require('electron').remote;
let listeners = {
    resize: {},
    menus: {},
    user: {}
}

ipcRenderer.on('sys-win-resize', (event, args) => {
    console.log('sys-win-resize')
   const { winid, bounds } = args;
   const ls = listeners.resize[winid] || [];
   ls.forEach((item) => {
       if (typeof item === 'function') {
           item(bounds);
       }
   });
});

ipcRenderer.on('context-menu', (event, args) => {
    const ls = listeners.menus[args] || [];
    ls.forEach((item) => {
       if (typeof item === 'function') {
           item();
       }
    });
});

function openWin(option) {
    return ipcRenderer.invoke('user-open-win', option);
}

function closeWin(uid) {
    return ipcRenderer.invoke('user-close-win', uid);

}

function resize(uid, width, height) {
    return ipcRenderer.invoke('user-resize-win', {
        uid,
        width,
        height
    });
}

function emit(uid, event) {
    if (event === 'context-menu') {
        const ls = listeners.menus[uid] || [];
        ls.forEach((item) => {
            if (typeof item === 'function') {
                item();
            }
        });
    } else if (event === 'user') {
        const ls = listeners.user[uid] || [];
        ls.forEach((item) => {
            if (typeof item === 'function') {
                item();
            }
        });
    }

}

function addEventListener(uid, event, listener) {
    if (event === 'resize') {
        const ls = listeners.resize[uid] || [];
        ls.push(listener);
        listeners.resize[uid] = ls;
    } else if (event === 'context-menu') {
        const ls = listeners.menus[uid] || [];
        ls.push(listener);
        listeners.menus[uid] = ls;
    } else if (event === 'user') {
        const ls = listeners.user[uid] || [];
        ls.push(listener);
        listeners.user[uid] = ls;
    }
}

function move(uid, px, py) {
    return ipcRenderer.invoke('user-move-win', {
        uid,
        x: px,
        y: py
    });
}

function showOpenDialog(options) {
    return dialog.showOpenDialog(options);
}



export function injectWin(XUE) {
    XUE.win = {
        openWin,
        closeWin,
        resize,
        move,
        addEventListener,
        emit,
        showOpenDialog,
        get winid() {
            let query = window.location.search.substring(1);
            let vars = query.split('&');
            for(let i = 0; i < vars.length; i++) {
                let pair = vars[i].split('=');
                if (pair[0] === 'winid') {
                    return pair[1];
                }
            }
            return null;
        }
    };
}
